package com.lyw.forum.service.impl;

import com.lyw.forum.common.enums.ResultCode;
import com.lyw.forum.common.exception.ApplicationException;
import com.lyw.forum.common.utils.BeanTransUtils;
import com.lyw.forum.common.utils.SetDefaultUtils;
import com.lyw.forum.mapper.ArticleReplyMapper;
import com.lyw.forum.pojo.dataobject.ArticleReply;
import com.lyw.forum.pojo.request.ArticleReplyCreateRequest;
import com.lyw.forum.pojo.response.AppResult;
import com.lyw.forum.pojo.response.ArticleReplySelectResponse;
import com.lyw.forum.service.IArticleReplyService;
import com.lyw.forum.service.IArticleService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Resource
    private ArticleReplyMapper articleReplyMapper;

    @Resource
    private IArticleService articleService;

    @Override
    public void creat(ArticleReplyCreateRequest articleReplyCreateRequest) {
        //转化
        ArticleReply articleReply = BeanTransUtils.transArticleReplyCreateRequest(articleReplyCreateRequest);

        //设置默认值 减少数据库性能的开销
        ArticleReply articleReplyRequest = SetDefaultUtils.setArticleReplyRequestDefault(articleReply);

        //写入数据库
        int result = 0;
        try {
            result = articleReplyMapper.insert(articleReplyRequest);
        } catch (Exception e) {
            //打印日志
            log.error(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }

        if (result != 1) {
            //打印日志
            log.error(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }

        //更新帖子表中的回复数量
        articleService.addOneReplyCountById(articleReplyCreateRequest.getArticleId());

        //打印日志
        log.info("创建帖子回复成功, ArticleReplyId: " + articleReplyRequest.getId() + "" +
                ", userId: " + articleReplyRequest.getPostUserId() + ", articleId: "
                + articleReplyRequest.getArticleId());
    }

    @Override
    public List<ArticleReplySelectResponse> selectByArticleId(Integer id) {
        //调用mapper查询结果
        List<ArticleReply> articleReplies = articleReplyMapper.selectByArticleId(id);

        //结果转化
        List<ArticleReplySelectResponse> articleReplySelectResponses = BeanTransUtils.transArticleReply(articleReplies);

        //返回结果
        return articleReplySelectResponses;
    }
}
